//
//  AppDelegate.m
//  KD
//
//  Created by Hubery on 16/1/11.
//  Copyright © 2016年 Whx. All rights reserved.
//

#import "AppDelegate.h"
#import <IQKeyboardManager.h>
#import "HXTabBarViewController.h"
#import "HXNotifyDetailsViewController.h"
#import "HXMeetingNotifyDetailsViewController.h"
#import "HXSelectedViewController.h"
#import "JCHATFileManager.h"
#import "JCHATCustomFormatter.h"
#import "JCHATContactsViewController.h"
#import "JCHATTabBarViewController.h"
#import "JCHATUserInfoViewController.h"
#import "JCHATConversationListViewController.h"
#import "HXNavigationController.h"
#import "HXFileDetailsViewController.h"
#import "HXJobRecordTableViewController.h"
#import "HXMeViewController.h"
#import "HXGroupJobTableViewController.h"
#import "HXCompanyNotifyTableViewController.h"

#import "EBForeNotification.h"//模拟后台通知弹窗
#import "HXCompanyInformTableViewController.h"

@interface AppDelegate ()<UIAlertViewDelegate>
@property(nonatomic,strong)  BMKMapManager* mapManager;
@property (nonatomic,strong) JCHATTabBarViewController *tabBarCtl;
@property (nonatomic,strong) HXTabBarViewController * hxTabBar;

@property (nonatomic,assign) BOOL isBackGround;
@property (nonatomic,assign) BOOL isJump;
@property (nonatomic,assign) BOOL isFirstRemind;
@property (nonatomic,assign) BOOL isHaveComeInGJTVC;
@property (nonatomic,assign) BOOL isHaveComeInIflyNotify;

@end

@implementation AppDelegate

+ (void)registerLocalNotification:(NSInteger)alertTime{

    
}
//-------- 加载其他的方面
-(void) loadCreateViewOther {
    // 定位提醒
    [[CCLocationManager shareLocation] getCity:^(NSString *addressString) {
    }];
    
    //初始化本地数据库
    [MagicalRecord setupCoreDataStack];
    
    [self mapManager];//百度地图
    
    //SVProgressHUD 及 键盘
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
    [SVProgressHUD setMinimumDismissTimeInterval:0.8];
    [[IQKeyboardManager sharedManager] setEnable:YES];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    [IQKeyboardManager sharedManager].canAdjustTextView = YES;
    [IQKeyboardManager sharedManager].shouldToolbarUsesTextFieldTintColor = YES;
    [IQKeyboardManager sharedManager].enableAutoToolbar = NO;
}

//-------- 判断登录状态
-(void) loadCreateViewLogIn {
    if (![[UserDefaultHandler getUserDetault:kNotFirstLogin] boolValue]) {
        //首次启动App
        [UserDefaultHandler initUserDefault];
    }
    
    if ([[UserDefaultHandler getUserDetault:kRemember] isEqualToString:RememberPwd]) {//是否记住密码
        if (![GlobalUtil isNilValue:[UserDefaultHandler getUserDetault:kID]]) {//已登录过
            HXTabBarViewController * hxTabBar = [[HXTabBarViewController alloc] init];
            [UserDefaultHandler saveUserDetault:@"yes" key:kNormalIn];
            hxTabBar.userKind = [UserDefaultHandler getUserDetault:kUsers_Kind];
            self.window.rootViewController = hxTabBar;
        }else{//没登录
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"HXLoginRegister" bundle:nil];
            HXSelectedViewController *hxSelectedVC = [storyBoard instantiateViewControllerWithIdentifier:@"HXSelectedViewController"];
            self.window.rootViewController = hxSelectedVC;
            NSString *str = [UserDefaultHandler getUserDetault:kUsers_CellPhoneNum];
            [UserDefaultHandler initUserDefault];
            [UserDefaultHandler saveUserDetault:str key:kUsers_CellPhoneNum];
            [UserDefaultHandler saveUserDetault:@"no" key:kNormalIn];
        }
    }else{//没记住密码
        UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"HXLoginRegister" bundle:nil];
        HXSelectedViewController *hxSelectedVC = [storyBoard instantiateViewControllerWithIdentifier:@"HXSelectedViewController"];
        self.window.rootViewController = hxSelectedVC;
        NSString *str = [UserDefaultHandler getUserDetault:kUsers_CellPhoneNum];
        [UserDefaultHandler initUserDefault];
        [UserDefaultHandler saveUserDetault:str key:kUsers_CellPhoneNum];
        [UserDefaultHandler saveUserDetault:@"no" key:kNormalIn];
    }
}

//-------- 设置极光
-(void) loadCreateViewJiGuangWithOptions:(NSDictionary *)launchOptions {
    // 极光推送
    [self initLogger];
    // init third-party SDK
    [JMessage addDelegate:self withConversation:nil];
    /// Required - 启动 JMessage SDK
    [JMessage setupJMessage:launchOptions
                     appKey:JPUSH_KEY
                    channel:nil
           apsForProduction:NO
                   category:nil];
    [JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
    [self registerJPushStatusNotification];
}

#pragma - mark JMessageDelegate
- (void)onLoginUserKicked {
    UIAlertView *alertView =[[UIAlertView alloc] initWithTitle:@"下线提示"
                                                       message:@"您的账号已经在另一台设备上登录,您被迫下线"
                                                      delegate:self
                                             cancelButtonTitle:nil
                                             otherButtonTitles:@"确定", nil];
    alertView.tag = 1200;
    [alertView show];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *str = [UserDefaultHandler getUserDetault:kUsers_CellPhoneNum];
    [UserDefaultHandler initUserDefault];
    [UserDefaultHandler saveUserDetault:str key:kUsers_CellPhoneNum];
    UIWindow *win = [[UIApplication sharedApplication].delegate window];
    UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"HXLoginRegister" bundle:nil];
    HXSelectedViewController *hxSelectedVC = [storyBoard instantiateViewControllerWithIdentifier:@"HXSelectedViewController"];
    win.rootViewController = hxSelectedVC;
    [win makeKeyAndVisible];
    [JMSGUser logout:^(id resultObject, NSError *error) {
        NSLog(@"Logout callback with - %@", error);
    }];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kuserName];
    return;
}


#pragma mark --初始化各个功能模块
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //初始化
    _isJump = NO;
    _isBackGround = NO;
    _isHaveComeInGJTVC = YES;
    
    //初始化极光
    [self loadCreateViewJiGuangWithOptions:launchOptions];
    
    //初始化窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //加载其他方面
    [self loadCreateViewOther];
    //设置登录状态
    [self loadCreateViewLogIn];
    
    [JCHATFileManager initWithFilePath];//demo 初始化存储路径
    
    return YES;
}

- (void)initLogger {
    JCHATCustomFormatter *formatter = [[JCHATCustomFormatter alloc] init];
    
    // XCode console
    [[DDTTYLogger sharedInstance] setLogFormatter:formatter];
    [DDLog addLogger:[DDTTYLogger sharedInstance]];
    
    // Apple System
    [[DDASLLogger sharedInstance] setLogFormatter:formatter];
    [DDLog addLogger:[DDASLLogger sharedInstance]];
    DDFileLogger *fileLogger = [[DDFileLogger alloc] init];
    fileLogger.rollingFrequency = 60 * 60 * 24; // 一个LogFile的有效期长，有效期内Log都会写入该LogFile
    fileLogger.logFileManager.maximumNumberOfLogFiles = 7;//最多LogFile的数量
    [fileLogger setLogFormatter:formatter];
    [DDLog addLogger:fileLogger];
}

- (void)registerJPushStatusNotification {
    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidSetup:)
                          name:kJPFNetworkDidSetupNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkIsConnecting:)
                          name:kJPFNetworkIsConnectingNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidClose:)
                          name:kJPFNetworkDidCloseNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidRegister:)
                          name:kJPFNetworkDidRegisterNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(networkDidLogin:)
                          name:kJPFNetworkDidLoginNotification
                        object:nil];
    [defaultCenter addObserver:self
                      selector:@selector(receivePushMessage:)
                          name:kJPFNetworkDidReceiveMessageNotification
                        object:nil];
    
    //日报的通知  进入
    [defaultCenter addObserver:self
                      selector:@selector(dealWithJPUSH_HaveComeIn:)
                          name:@"NOTIFICATION_HaveComeInGJTVC"
                        object:nil];
    
    //日报的通知 出去
    [defaultCenter addObserver:self
                      selector:@selector(dealWithJPUSH_HaveGoOut:)
                          name:@"NOTIFICATION_HaveGoOutGJTVC"
                        object:nil];
    
    //公司内部通知 出去
    [defaultCenter addObserver:self
                      selector:@selector(dealWithJPUSH_IflyNotify_HaveGoOut:)
                          name:@"NOTIFICATION_HaveComeOutIflyNotify"
                        object:nil];
    
    //公司内部通知 进入
    [defaultCenter addObserver:self
                      selector:@selector(dealWithJPUSH_IflyNotify_HaveComeIn:)
                          name:@"NOTIFICATION_HaveComeInIflyNotify"
                        object:nil];
    
    
    [defaultCenter addObserver:self
                      selector:@selector(click_EBBannerViewDidClick:)
                          name:EBBannerViewDidClick
                        object:nil];
}

/**点击弹窗的调用方法*/
-(void)click_EBBannerViewDidClick:(NSNotification *)notification{

    NSLog(@"dddnotification ----------%@---------------",notification);
    NSDictionary * userInfo = (NSDictionary *)notification.object;
    UIWindow *win = [[UIApplication sharedApplication].delegate window];
    HXTabBarViewController *tabVc = (HXTabBarViewController *)win.rootViewController;
    
    NSArray *allKeysArray = [userInfo allKeys];
    for (NSString * keyString in allKeysArray) {
        if ([keyString isEqualToString:@"Document"]) {
            //            [[NSNotificationCenter defaultCenter] postNotificationName:nFile object:@{@"A":str}];//公文通知
            UIWindow *win = [[UIApplication sharedApplication].delegate window];
            HXTabBarViewController *tabVc = (HXTabBarViewController *)win.rootViewController;
            tabVc.selectedIndex = 1;
            HXNavigationController *naVc = tabVc.childViewControllers[1];
            HXFileDetailsViewController *vc = [[HXFileDetailsViewController alloc]init];
            NSString *idstr = [userInfo objectForKey:@"Document"];
            vc.dataId = idstr;
            [naVc pushViewController:vc animated:YES];
        }else if ([keyString isEqualToString:@"Message"]) {//通知
            [[NSNotificationCenter defaultCenter] postNotificationName:nMessage object:nil];//消息通知
        }else if ([keyString isEqualToString:@"CorpMessage"]){//公司通知公告
            
            tabVc.selectedIndex = 0;
            [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_DealWithJPUSH_IflyNotify" object:nil userInfo:userInfo];
            
        }else if ([keyString isEqualToString:@"DayWorkGroupID"]) {//公司日报推送
            
            tabVc.selectedIndex = 1;
            HXNavigationController *naVc = tabVc.childViewControllers[1];
            HXGroupJobTableViewController * vc = [[HXGroupJobTableViewController alloc] initWithGroupId:[userInfo objectForKey:@"DayWorkGroupID"]];
            
            if (_isBackGround) {
                _isBackGround = NO;
                if (_isHaveComeInGJTVC) {
                    [naVc pushViewController:vc animated:YES];
                }else{
                    [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_DealWithJPUSH" object:nil userInfo:userInfo];
                }
                
            }else if(1){
                if (!_isFirstRemind) {
                    _isFirstRemind = YES;
                    if (_isJump) {
                        [[NSNotificationCenter defaultCenter] postNotificationName:@"NOTIFICATION_DealWithJPUSH" object:nil userInfo:userInfo];
                        _isFirstRemind = NO;
                    }else{
                        _isFirstRemind = NO;
                        [naVc pushViewController:vc animated:YES];
                    }
                }
            }
            
        }else if ([keyString isEqualToString:@"offline"]) {//退出登录
            //            [[NSNotificationCenter defaultCenter] postNotificationName:nOutLogin object:nil];//退出登录
            NSString *str = [UserDefaultHandler getUserDetault:kUsers_CellPhoneNum];
            [UserDefaultHandler initUserDefault];
            [UserDefaultHandler saveUserDetault:str key:kUsers_CellPhoneNum];
            UIWindow *win = [[UIApplication sharedApplication].delegate window];
            UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:@"HXLoginRegister" bundle:nil];
            HXSelectedViewController *hxSelectedVC = [storyBoard instantiateViewControllerWithIdentifier:@"HXSelectedViewController"];
            win.rootViewController = hxSelectedVC;
            [win makeKeyAndVisible];
            /**退出极光登录*/
            [JMSGUser logout:^(id resultObject, NSError *error) {
                if (error == nil) {
                    DDLogDebug(@"Action logout success");
                }
            }];
            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"
                                                          message:@"您的账号在别处登录,已退出登录"
                                                         delegate:self
                                                cancelButtonTitle:@"确定"
                                                otherButtonTitles: nil];
            [alert show];
        }else{
            DDLogDebug(@"Action logout success");
        }
    }
}

// notification from JPush
- (void)networkDidSetup:(NSNotification *)notification {
    DDLogDebug(@"Event - networkDidSetup");
    NSLog(@"建立连接===%@",notification.userInfo);
}

// notification from JPush
- (void)networkIsConnecting:(NSNotification *)notification {
    DDLogDebug(@"Event - networkIsConnecting");
    NSLog(@"正在连接中===%@",notification.userInfo);

}

// notification from JPush
- (void)networkDidClose:(NSNotification *)notification {
    DDLogDebug(@"Event - networkDidClose");
    NSLog(@"关闭连接===%@",notification.userInfo);

}

// notification from JPush
- (void)networkDidRegister:(NSNotification *)notification {
    DDLogDebug(@"Event - networkDidRegister");
    NSLog(@"注册成功===%@",notification.userInfo);

}

// notification from JPush
- (void)networkDidLogin:(NSNotification *)notification {
    
    if ([JPUSHService registrationID]) {
        
        NSString * registrationiD = [JPUSHService registrationID];
        NSLog(@"registrationiD ---------------registrationiD --is----%@----",registrationiD);
        DDLogDebug(@"Event - networkDidLogin");
        NSLog(@"登录成功===%@",notification.userInfo);
    }
    

}

// notification from JPush  // 收到自定义消息(非APNS)
- (void)receivePushMessage:(NSNotification *)notification {
    DDLogDebug(@"Event - receivePushMessage");
    
    NSDictionary *info = notification.userInfo;
    if (info) {
        DDLogDebug(@"The message - %@", info);
    } else {
        DDLogWarn(@"Unexpected - no user info in jpush mesasge");
    }
}



- (void)onDBMigrateStart {
    NSLog(@"onDBmigrateStart in appdelegate");
    _isDBMigrating = YES;
}

- (void)onDBMigrateFinishedWithError:(NSError *)error {
    NSLog(@"onDBmigrateFinish in appdelegate");
    _isDBMigrating = NO;
    [[NSNotificationCenter defaultCenter] postNotificationName:kDBMigrateFinishNotification object:nil];
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    DDLogDebug(@"Action - applicationDidEnterBackground");
    // Use this method to release shared resources, save user data, invalidate
    // timers, and store enough application state information to restore your
    // application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called
    // instead of applicationWillTerminate: when the user quits.
    
    _isBackGround = YES;
    
    [self resetApplicationBadge];
}

- (void)resetApplicationBadge {
    NSInteger badge = [[[NSUserDefaults standardUserDefaults] objectForKey:kBADGE] integerValue];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge];
    [JPUSHService setBadge:badge];
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    DDLogDebug(@"Action - applicationWillEnterForeground");
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the
    // application was inactive. If the application was previously in the
    // background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    DDLogVerbose(@"Action - applicationWillTerminate");
    // Called when the application is about to terminate. Save data if
    // appropriate. See also applicationDidEnterBackground:.
}


// ---------------------- JPUSH
// 通常会调用 JPUSHService 方法去完成 Push 相关的功能

- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    DDLogInfo(@"Action - didRegisterForRemoteNotificationsWithDeviceToken");
    DDLogVerbose(@"Got Device Token - %@", deviceToken);
    
    [JPUSHService registerDeviceToken:deviceToken];
}

- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    DDLogVerbose(@"Action - didFailToRegisterForRemoteNotificationsWithError - %@", error);
}

#if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_7_1

- (void)application:(UIApplication *)application
didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings {
    DDLogInfo(@"Action - didRegisterUserNotificationSettings");
}

// Called when your app has been activated by the user selecting an action from
// a local notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forLocalNotification:(UILocalNotification *)notification
  completionHandler:(void (^)())completionHandler {
    DDLogDebug(@"Action - handleActionWithIdentifier:forLocalNotification");
}

// Called when your app has been activated by the user selecting an action from
// a remote notification.
// A nil action identifier indicates the default action.
// You should call the completion handler as soon as you've finished handling
// the action.
- (void)application:(UIApplication *)application
handleActionWithIdentifier:(NSString *)identifier
forRemoteNotification:(NSDictionary *)userInfo
  completionHandler:(void (^)())completionHandler {
    DDLogDebug(@"Action - handleActionWithIdentifier:forRemoteNotification");
}

#endif // end of - > __IPHONE_7_1

- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    DDLogDebug(@"Action - didReceiveRemoteNotification");
    NSLog(@"推送通知内容打印一====================%@",userInfo);
    [EBForeNotification handleRemoteNotification:userInfo soundID:1312 isIos10:NO];
    DDLogVerbose(@"收到通知 - %@", [JCHATStringUtils dictionary2String:userInfo]);
}


#pragma mark ---------- 以下是 处理极光推送通知用的 ------------

/**
 通知的处理事件
 */
//通知 ---- 出去
-(void)dealWithJPUSH_IflyNotify_HaveGoOut:(NSNotification *)notification{
    
    NSLog(@"---------notification is %@",notification);
    
    _isHaveComeInIflyNotify = NO;
}

//进去
-(void)dealWithJPUSH_IflyNotify_HaveComeIn:(NSNotification *)notification{
    
    NSLog(@"---------notification is %@",notification);
    
    _isHaveComeInIflyNotify = YES;
}



//日报通知
-(void)dealWithJPUSH_HaveComeIn:(NSNotification *)notification{
    
    NSLog(@"---------notification is %@",notification);
    
    _isJump = YES;
    _isHaveComeInGJTVC = NO;
}
-(void)dealWithJPUSH_HaveGoOut:(NSNotification *)notification{
    
    NSLog(@"---------notification is %@",notification);
    
    _isJump = NO;
    _isHaveComeInGJTVC = YES;
}

/**
 销毁通知
 */
//-(void)dealloc{
//    
//    [[NSNotificationCenter defaultCenter] removeObserver:self];
//}

#pragma mark -------- 以上是处理极光推送所用的通知 ------------
#pragma mark 接收推送的消息
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"收到通知信息打印二============== ---- %@", userInfo);
//    DDLogDebug(@"Action - didReceiveRemoteNotification:fetchCompletionHandler");
    [EBForeNotification handleRemoteNotification:userInfo soundID:0 isIos10:NO];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    NSLog(@"收到通知信息打印三============== ---- %@", notification.userInfo);
    DDLogDebug(@"Action - didReceiveLocalNotification");
    [JPUSHService showLocalNotificationAtFront:notification identifierKey:nil];
}

// ---------- end of JPUSH

//
////拿到deviceToken
//- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
//
//    [JPUSHService registerDeviceToken:deviceToken];
//}
////远程通知点击
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
//    
//    // Required,For systems with less than or equal to iOS6
//    [JPUSHService handleRemoteNotification:userInfo];
//}
//
//- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
//    
//    // IOS 7 Support Required
//    [JPUSHService handleRemoteNotification:userInfo];
//    completionHandler(UIBackgroundFetchResultNewData);
//}
//
//- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
//    
//    //Optional
//    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
//}

-(BMKMapManager *)mapManager{
    if (!_mapManager) {
        _mapManager = [[BMKMapManager alloc]init];
        // 如果要关注网络及授权验证事件，请设定     generalDelegate参数
        BOOL ret = [_mapManager start:BAIDU_MAPKEY  generalDelegate:nil];
        if (!ret) {
            HXLog(@"百度地图授权失败");
        }else{
            //HXLog(@"百度地图授权成功");
        }
    }
    return _mapManager;
}

@end
